# -*- coding: UTF-8 -*-
"""
@Project ：swift-forge-engine
@File    ：health_check.py
@IDE     ：PyCharm 
@Author  ：Tony.Gan
@Date    ：2025/1/19 18:08 
@Des     ：
"""
import re
from math import ceil

from fastapi import FastAPI, Request, Response
from fastapi.routing import APIRoute

from App.common.exception.errors import HTTPError
from App.common.respones.response_code import CustomResponseCode


def normalize_path(path: str) -> str:
    # 将所有的路径参数都替换成统一的名称，如 `{param}`
    return re.sub(r"{[^}]*}", "{param}", path)


def ensure_unique_route_names(app: FastAPI) -> None:
    """
    检查路由名称是否唯一

    :param app:
    :return:
    """
    temp_routes = set()
    for route in app.routes:
        if isinstance(route, APIRoute):
            # 将路径统一规范化处理后再进行比较
            normalized_path = normalize_path(route.path)
            # 创建一个标识了路径和方法组合的签名
            if (normalized_path, frozenset(route.methods)) in temp_routes:
                raise ValueError(f'路由路径冲突: {route.path} {route.methods}')
            temp_routes.add((normalized_path, frozenset(route.methods)))


async def http_limit_callback(request: Request, response: Response, expire: int):
    """
    请求限制时的默认回调函数

    :param request:
    :param response:
    :param expire: 剩余毫秒
    :return:
    """
    expires = ceil(expire / 1000)
    raise HTTPError(code=CustomResponseCode.HTTP_429.code, message=CustomResponseCode.HTTP_429.message, headers={'Retry-After': str(expires)})